package com.example.sm2.controller;

import com.example.sm2.util.SM2Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * SM2加解密控制器
 * 提供REST接口用于密钥生成、加密和解密
 */
@RestController
@RequestMapping("/api/sm2")
@RequiredArgsConstructor
public class SM2Controller {
    
    private final SM2Utils sm2Utils;
    
    /**
     * 生成SM2密钥对
     * @return 包含公钥和私钥的响应
     */
    @GetMapping("/generate-key-pair")
    public Map<String, String> generateKeyPair() {
        return sm2Utils.generateKeyPair();
    }
    
    /**
     * 使用SM2公钥加密数据
     * @param request 包含公钥和待加密数据的请求体
     * @return 加密后的结果
     */
    @PostMapping("/encrypt")
    public Map<String, String> encrypt(@RequestBody SM2EncryptRequest request) {
        String encryptedData = sm2Utils.encrypt(request.getPublicKey(), request.getData());
        
        Map<String, String> response = new HashMap<>(1);
        response.put("encryptedData", encryptedData);
        return response;
    }
    
    /**
     * 使用SM2私钥解密数据
     * @param request 包含私钥和加密数据的请求体
     * @return 解密后的结果
     */
    @PostMapping("/decrypt")
    public Map<String, String> decrypt(@RequestBody SM2DecryptRequest request) {
        String decryptedData = sm2Utils.decrypt(request.getPrivateKey(), request.getEncryptedData());
        
        Map<String, String> response = new HashMap<>(1);
        response.put("decryptedData", decryptedData);
        return response;
    }
    
    /**
     * 加密请求参数类
     */
    public static class SM2EncryptRequest {
        private String publicKey;
        private String data;
        
        // Getters and Setters
        public String getPublicKey() {
            return publicKey;
        }
        
        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }
        
        public String getData() {
            return data;
        }
        
        public void setData(String data) {
            this.data = data;
        }
    }
    
    /**
     * 解密请求参数类
     */
    public static class SM2DecryptRequest {
        private String privateKey;
        private String encryptedData;
        
        // Getters and Setters
        public String getPrivateKey() {
            return privateKey;
        }
        
        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
        
        public String getEncryptedData() {
            return encryptedData;
        }
        
        public void setEncryptedData(String encryptedData) {
            this.encryptedData = encryptedData;
        }
    }
}
